
import time
import os
import threading
import random
import hashlib


def to_time(s_datetime=None):  # 日期时间转时间戳
    if s_datetime is None:  # 没有传入时间，直接返回当前时间戳
        ret_time = time.time()
    elif ':' in s_datetime:  # 日期时间
        ret_time = time.mktime(time.strptime(str(s_datetime), "%Y-%m-%d %H:%M:%S"))
    else:  # 日期
        ret_time = time.mktime(time.strptime(str(s_datetime), "%Y-%m-%d"))
    return int(ret_time)


def to_datetime(s_time=None, to_str='%Y-%m-%d %H:%M:%S'):  # 时间戳转日期时间
    return time.strftime(to_str, time.localtime(s_time))


def nonce_str(length=32):  # 随机字符串
    vvv = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'  # 随机种子
    nonce_str_list = list()
    for _ in range(length):
        nonce_str_list.append(random.choice(vvv))  # 从随机种子里面随机获取一个字符
    random.shuffle(nonce_str_list)  # 再次打乱
    return ''.join(nonce_str_list)


def md5(value):  # 获取md5
    if type(value) != bytes:
        value = str(value).encode()
    m2 = hashlib.md5()
    m2.update(value)
    return m2.hexdigest()


def file_wr(file_path, body=None, append=False, encoding='utf-8'):  # 读取，写入文件
    """
    读取，写入文件
    :param file_path: 文件路径
    :param body: 写入的文件内容，值为None时，读取文件
    :param append: 是否追加写入，True为追加
    :param encoding: 字符格式
    :return:  写入文件返回写入的长度，读取文件返回读取的内容
    """
    if body is None:  # 判断是否读取，body is None 为读取数据
        if os.path.isfile(file_path):
            file_m = open(file_path, 'r', encoding=encoding)
            file_str = file_m.read()
            file_m.close()
        else:
            file_str = None
        return file_str
    else:  # 写入数据
        open_mode = 'a' if append else 'w'
        file_m = open(file_path, open_mode, encoding=encoding)
        w_len = file_m.write(body)
        file_m.close()
        return w_len


def down_file(url, path, headers={}):  # 下载文件
    req = __import__('requests')
    w_file = open(path, 'wb+')
    ret = req.get(url, headers=headers)
    w_c = w_file.write(ret.content)
    w_file.close()
    return w_c


def date_between(s_date, e_date):  # 根据开始结束日期返回区间日期
    date_list = []
    for i in range(int(to_time(s_date)), int(to_time(e_date))+1, 86400):
        date_list.append(to_datetime(i, to_str='%Y-%m-%d'))
    return date_list


def thread(target=None, args=(), kwargs={}, name=None):  # 线程
    """
        :param target: 要调用的目标对象
        :param args: 要传入到目标对象的参数
        :param name: 线程名称
        :return: 返回线程对象
    """
    xc = threading.Thread(target=target, args=args, kwargs=kwargs, name=name)
    return xc


if __name__ == '__main__':
    pass













